﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using WebApiV3.Data;

namespace WebApiV3.Domain
{
    public class EfRespository<T> : IRespository<T> where T : BaseEntity
    {
        private readonly Admin10086525DbContext db;

        private DbSet<T> _entity;

        private DbSet<T> Entity
        {
            get
            {
                if (_entity==null)
                {
                    _entity = db.Set<T>();
                }
                return _entity;
            }
        }

        public IQueryable<T> Table
        {
            get
            {
                return Entity;
            }
        }

        public EfRespository(Admin10086525DbContext dbContext)
        {
            db = dbContext;
        }
        public void Delete(T entity)
        {
            db.Remove(entity);
            db.SaveChanges();
        }

        public void Delete(int id)
        {
            var res = Entity.Where(x => x.Id == id).FirstOrDefault();
            Delete(res);
        }

        public T GetById(int id)
        {
            return Entity.Where(x => x.Id == id).FirstOrDefault();
        }

        public void Insert(T entity)
        {
            db.Add(entity);
            db.SaveChanges();
        }

        public void InsertBule(IEnumerable<T> entity)
        {
            db.AddRange(entity);
            db.SaveChanges();
        }

        public void Update(T entity)
        {
            db.Update(entity);
            db.SaveChanges();
        }

        public void Delete(IEnumerable<T> entityes)
        {
            Entity.RemoveRange(entityes);
            db.SaveChanges();
        }
    }
}
